import { legacyLogicalPropertiesTransformer, StyleProvider } from '@ant-design/cssinjs';
import { AlertOutlined, CopyrightOutlined, InfoCircleFilled } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { Alert, Button, Tag } from 'antd';
import React from 'react';
import defaultSettings from '../config/defaultSettings';
import Footer from './components/Footer';
import { AvatarDropdown, AvatarName } from './components/RightContent/AvatarDropdown';
import WeChatDrawer from './components/WeChatDrawer';
import { requestConfig } from './requestConfig';
import { currentAccount } from './services/api/api-login';
import { isWeChatBrowser } from './utils/browser';
import { parse } from './utils/historyUtils';

const loginPath = '/user/login';
const loginBindPath = '/user/bind';
const loginWeChatPath = '/user/wechat';
const loginSelectPath = '/user/select';
const loginNestedPath = '/user/nested';
const loginBrainPath = '/user/brain';
const cuesAnalysisWxPath = '/cues/analysisWx';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: AccountData.CurrentAccountVo;
  loading?: boolean;
  fetchUserInfo?: () => Promise<AccountData.CurrentAccountVo | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await currentAccount({
        skipErrorHandler: true,
      });
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const { location } = history;

  if (
    location.pathname.indexOf(loginPath) === -1 &&
    location.pathname.indexOf(loginBindPath) === -1 &&
    location.pathname.indexOf(loginWeChatPath) === -1 &&
    location.pathname.indexOf(loginSelectPath) === -1 &&
    location.pathname.indexOf(loginNestedPath) === -1 &&
    location.pathname.indexOf(loginBrainPath) === -1
  ) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }

  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    // actionsRender: () => [<Question key="doc" />, <SelectLang key="SelectLang" />],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return (
          <>
            {initialState?.currentUser?.isHasSelectLoginOrganization === 1 ? (
              <Tag
                color="#f50"
                onClick={() => {
                  history.push('/user/select?accountId=' + initialState?.currentUser?.id);
                }}
              >
                切换单位
              </Tag>
            ) : (
              <></>
            )}
            <AvatarDropdown menu={true}>{avatarChildren}</AvatarDropdown>
          </>
        );
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login

      const { token, route } = parse(location.search) as {
        token: string;
        route: string;
      };

      if (
        !initialState?.currentUser &&
        location.pathname.indexOf(loginPath) !== -1 &&
        location.pathname.indexOf(loginBindPath) !== -1 &&
        location.pathname.indexOf(loginWeChatPath) !== -1 &&
        location.pathname.indexOf(loginSelectPath) === -1 &&
        location.pathname.indexOf(loginNestedPath) !== -1 &&
        location.pathname.indexOf(loginBrainPath) !== -1
      ) {
        history.push(loginPath);
      }
    },
    layoutBgImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    bgLayoutImgList: [
      {
        src: 'https://img.alicdn.com/imgextra/i2/O1CN01O4etvp1DvpFLKfuWq_!!6000000000279-2-tps-609-606.png',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://img.alicdn.com/imgextra/i2/O1CN01O4etvp1DvpFLKfuWq_!!6000000000279-2-tps-609-606.png',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://img.alicdn.com/imgextra/i3/O1CN018NxReL1shX85Yz6Cx_!!6000000005798-2-tps-884-496.png',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: [
      <a
        key="miit"
        href="https://beian.miit.gov.cn/"
        target="_blank"
        rel="noopener noreferrer"
        style={{
          display: 'block',
          textAlign: 'center',
        }}
      >
        <AlertOutlined />
        <span>渝ICP备2021004499号</span>
      </a>,
      <a key="company" href="https://cqgdrm.com/home" target="_blank" rel="noopener noreferrer">
        <CopyrightOutlined />
        <span>{`重庆广电数字技术有限责任公司`}</span>
      </a>,
    ],
    ...initialState?.settings,
    // splitMenus: false,
    headerRender: (props, defaultDom) => (
      <>
        {isWeChatBrowser() ? (
          <div>
            <Alert
              message={
                <div
                  style={{
                    color: 'white',
                  }}
                >
                  本网站提供的部分服务在你当前浏览器中无法使用，建议你更换为 Chrome 或 Edge
                  浏览器查看本网站。
                </div>
              }
              icon={
                <InfoCircleFilled
                  style={{
                    color: 'white',
                  }}
                />
              }
              banner
              style={{
                backgroundColor: 'black',
              }}
              action={
                <WeChatDrawer
                  trigger={
                    <Button
                      type="text"
                      style={{
                        color: 'white',
                      }}
                    >
                      查看详情
                    </Button>
                  }
                />
              }
            />
            {React.cloneElement(defaultDom as any, {
              style: {
                height: '56px',
                lineHeight: '56px',
              },
            })}
          </div>
        ) : (
          <>{defaultDom}</>
        )}
      </>
    ),
    // fixSiderbar: isModeNest(),
    token: {
      header: {
        // colorBgMenuItemSelected: 'rgba(0,0,0,0.04)',
        colorBgHeader: '#004FD9',
        colorHeaderTitle: '#fff',
        colorTextMenuSelected: '#fff',
        colorTextMenu: 'rgba(255,255,255,0.95)',
        colorTextMenuSecondary: 'rgba(255,255,255,0.65)',
        colorTextMenuActive: 'rgba(255,255,255,0.95)',
        colorBgMenuItemSelected: 'rgba(255,255,255,0.15)',
        heightLayoutHeader: isWeChatBrowser() ? 105 : 64,
      },
      bgLayout: '#fefefe',
      fontSize: 50,
    },
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  dataField: 'data',
  ...requestConfig,
};

export function rootContainer(container: React.ReactElement) {
  return React.createElement(
    StyleProvider,
    {
      hashPriority: 'high',
      transformers: [legacyLogicalPropertiesTransformer],
    },
    container,
  );
}
